import { ref, onUnmounted } from 'vue';
import axios from 'axios';

interface ChartDataItem {
  name: string;
  value: number;
}

export function useChartDataFetch(dataSource: any) {
  const data = ref<ChartDataItem[]>([]);
  let timer: number | null = null;
  
  const fetchData = async () => {
    try {
      let result: ChartDataItem[];
      
      switch (dataSource.type) {
        case 'static':
          result = JSON.parse(dataSource.data);
          break;
          
        case 'api':
          const response = await axios({
            url: dataSource.url,
            method: dataSource.method,
            data: JSON.parse(dataSource.params)
          });
          result = response.data;
          break;
          
        case 'sql':
          // 调用后端SQL查询接口
          const sqlResponse = await axios.post('/api/sql/query', {
            sql: dataSource.sql
          });
          result = sqlResponse.data;
          break;
          
        default:
          result = [];
      }
      
      data.value = result;
    } catch (error) {
      console.error('获取图表数据失败:', error);
      data.value = [];
    }
  };
  
  const startFetch = (interval = 0) => {
    fetchData();
    
    if (interval > 0) {
      timer = window.setInterval(fetchData, interval);
    }
  };
  
  const stopFetch = () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };
  
  onUnmounted(() => {
    stopFetch();
  });
  
  return {
    data,
    startFetch,
    stopFetch
  };
} 